package shiqi.exception;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @ Author     ：shiqi
 * @ Date       ：Created in 10:15 2020/5/23
 * @ Description：判断Controller是返回json还是页面的拦截器，为统一异常处理返回结果做判断依据
 * @Version: 1.0
 */
@Component
public class ExceptionPreHandleInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod hm = (HandlerMethod) handler;
        Method method = hm.getMethod();
        //Controller方法返回值是否为字符串
        boolean b1 = method.getReturnType().equals(String.class);
        //Controller方法是否使用@ResponseBody注解
        boolean b2 = !method.isAnnotationPresent(ResponseBody.class);
        //Controller是否使用@RestController注解
        boolean b3 = !hm.getBeanType().isAnnotationPresent(RestController.class);
        request.setAttribute("method_return_is_view", b1 && b2 && b3);
        return true;
    }
}
